package com.itlong.cloud.sdk.service.impl;

import com.itlong.cloud.POJO.DTO.sdk.CloudTalkSDKAppUserLoginDTO;
import com.itlong.cloud.POJO.PO.PropertyUserInfoPO;
import com.itlong.cloud.POJO.VO.sdk.CloudTalkSDKAPPAllDeviceListVO;
import com.itlong.cloud.POJO.VO.sdk.CloudTalkSDKAppDemoLoginVO;
import com.itlong.cloud.POJO.VO.sdk.CloudTalkSDKAppUserVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.SystemTypeEnum;
import com.itlong.cloud.sdk.dao.ICloudTalkSDKAppUserDao;
import com.itlong.cloud.sdk.service.ICloudTalkSDKAppUserService;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.encrypt.Md5;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <desc>
 *      云对讲SDK用户信息业务处理接口实现类
 * </desc>
 *
 * @createDate 2018/05/11
 */
@Service
@RefreshScope
public class CloudTalkSDKAppUserServiceImpl implements ICloudTalkSDKAppUserService{
    @Autowired
    ICloudTalkSDKAppUserDao iCloudTalkSDKAppUserDao;
    @Autowired
    RedisService redisService;

    @Value("${" + PlatformConstants.CLOUDTALK_SDK_USER_TOKEN_KEY + "}")
    String userTokenKey;

    /**
     * <desc>
     *      云对讲SDK用户登录
     * </desc>
     *
     * @param dto
     * @return null 验证appId失败 ，vo手机号为空 用户不存在
     * @author Jiaqi.X
     * @createDate 2018/05/11
     */
    @Override
    public CloudTalkSDKAppUserVO authentication(CloudTalkSDKAppUserLoginDTO dto) throws UnsupportedEncodingException {
        if(iCloudTalkSDKAppUserDao.checkSDKSecret(dto) > 0){
            CloudTalkSDKAppUserVO vo = iCloudTalkSDKAppUserDao.checkUserPhone(dto.getPhoneNo());
            if(StringUtils.isBlank(vo.getPhoneNo())){
                return vo;
            }else{
                vo.setExpiresIn("604800");
                vo.setToken(UserTokenUtil.tokenEncrypt(
                        vo.getPhoneNo(),userTokenKey, SystemTypeEnum.CLOUD_TALK_SDK_SERVER.getType()));
                //设置缓存
                redisService.set(RedisConstant.REDIS_CLOUDTALK_SDK_APP_USER_CACHE + vo.getPhoneNo(),RedisConstant.REDIS_CLOUDTALK_SDK_APP_USER_CACHE_TIME,vo);
                return vo;
            }
        }
        return null;
    }




    /**
     * <desc>
     *      云对讲SDK 登出
     * </desc>
     *
     * @param token
     * @author Jiaqi.X
     * @createDate 2018/05/14
     */
    @Override
    public void logout(String token) {
        redisService.del(RedisConstant.REDIS_CLOUDTALK_SDK_APP_USER_CACHE+UserTokenUtil.tokenDecrypt(token,userTokenKey));
    }

    /**
     * <desc>
     *      从缓存中获取用户信息
     * </desc>
     *
     * @param token 用户token
     * @return
     * @author Jiaqi.X
     * @createDate 2018/05/17
     */
    @Override
    public CloudTalkSDKAppUserVO retrieve(String token) {
        try {
            if (StringUtils.isBlank(token)) {
                return null;
            }
            //解密拿到手机号
            String phoneNum = UserTokenUtil.tokenDecrypt(token, userTokenKey);
            if (phoneNum == null) {
                return null;
            }
            CloudTalkSDKAppUserVO vo = (CloudTalkSDKAppUserVO) redisService.getObject(RedisConstant.REDIS_CLOUDTALK_SDK_APP_USER_CACHE + phoneNum,CloudTalkSDKAppUserVO.class);
            if (vo != null && token.equals(vo.getToken())) {
                return vo;
            } else {
                return null;
            }
        }catch (RedisConnectionFailureException e){
            throw new DataAccessException("云对讲SDKretrieve【从缓存中获取用户信息】redis连接失败") ;
        }
    }

    /**
     * <desc>
     *      通过手机号获取app用户id
     * </desc>
     *
     * @param phoneNum
     * @return
     * @author Jiaqi.X
     * @createDate 2018/05/14
     */
    @Override
    public String getUserIdByPhoneNum(String phoneNum){
        return iCloudTalkSDKAppUserDao.getUserIdByPhoneNum(phoneNum);
    }

    /**
     * <desc>
     *      demo登录
     * <desc/>
     *
     * @return 云对讲SDK APP demo登录VO对象
     * @author wangzhi
     * @createDate 2018/11/21
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public CloudTalkSDKAppDemoLoginVO cloudTalkLogin(String phoneNo, String pswd) throws Exception {
        pswd = Md5.En(pswd);
        CloudTalkSDKAppDemoLoginVO cloudTalkSDKAppDemoLoginVO = null;
        if (phoneNo.matches("^1[3|4|5|6|7|8|9]\\d{9}$")) {
            int count = iCloudTalkSDKAppUserDao.loginByPhoneNo(phoneNo, pswd);
            if (count == 0) {
                return null;
            }
            cloudTalkSDKAppDemoLoginVO = iCloudTalkSDKAppUserDao.getDeviceDataByPhoneNo(phoneNo, pswd);
        }
        if (phoneNo.matches("^[A-Za-z\\d]+([-_.][A-Za-z\\d]+)*@([A-Za-z\\d]+[-.])+[A-Za-z\\d]{2,4}$")) {
            int count = iCloudTalkSDKAppUserDao.loginByEmail(phoneNo, pswd);
            if (count == 0) {
                return null;
            }
            cloudTalkSDKAppDemoLoginVO = iCloudTalkSDKAppUserDao.getDeviceDataByEmail(phoneNo, pswd);
        }
        if (cloudTalkSDKAppDemoLoginVO != null) {
            List<CloudTalkSDKAPPAllDeviceListVO> allDeviceListVO = iCloudTalkSDKAppUserDao.getDeviceList(cloudTalkSDKAppDemoLoginVO.getRoomId());
            cloudTalkSDKAppDemoLoginVO.getAllDeviceList().addAll(allDeviceListVO);
        }
        return cloudTalkSDKAppDemoLoginVO;
    }

    /**
     * <desc>
     *      SDK开发者认证
     * <desc/>
     *
     * @return propertyUserInfoPO
     * @return robotId 机器人编号
     * @author Qiang.S
     * @createDate 2019/09/16
     */
    @Override
    public String developerLogin(PropertyUserInfoPO propertyUserInfoPO,String robotId) throws UnsupportedEncodingException {
        if (robotId == null) {
            robotId = "";
        }

        String token = UserTokenUtil.tokenEncrypt(propertyUserInfoPO.getUserId()+robotId + new SimpleDateFormat("MMddHHmmss").format(new Date()),
                userTokenKey, SystemTypeEnum.SDK_SERVER.getType());
        propertyUserInfoPO.setToken(token);
        //设置缓存
        redisService.set(RedisConstant.REDIS_CLOUDDEVICE_SDK_DEVELOPER_CACHE + propertyUserInfoPO.getUserId() + robotId,
                RedisConstant.REDIS_CLOUDDEVICE_SDK_DEVELOPER_CACHE_TIME, propertyUserInfoPO);
        return token;
    }

    /**
     * <desc>
     *      SDK开发者认证
     * <desc/>
     *
     * @return propertyUserInfoPO
     * @return robotId 机器人编号
     * @author Qiang.S
     * @createDate 2019/09/16
     */
    @Override
    public String robotGoDeveloperLogin(PropertyUserInfoPO propertyUserInfoPO,String robotId) throws UnsupportedEncodingException {
        if (robotId == null) {
            robotId = "";
        }
        //机器人token规则，为了防止机器人调试工具多端登录后token失效，给一个固定时间戳
        String token = UserTokenUtil.tokenEncrypt(propertyUserInfoPO.getUserId()+robotId + "0826103530",
                userTokenKey, SystemTypeEnum.SDK_SERVER.getType());
        propertyUserInfoPO.setToken(token);
        //设置缓存
        redisService.set(RedisConstant.REDIS_CLOUDDEVICE_SDK_DEVELOPER_CACHE + propertyUserInfoPO.getUserId() + robotId,
                RedisConstant.REDIS_CLOUDDEVICE_SDK_DEVELOPER_CACHE_TIME, propertyUserInfoPO);
        return token;
    }

    /**
     * <desc>
     * 设置消息回调的url地址
     * </desc>
     *
     * @param updateMessageCallbackRrl
     * @param projectId
     * @param userId
     * @Author chengshican
     * @Date 2020-11-19 19:27
     * @Param
     * @Return
     * @Exception
     */
    @Override
    public Integer updateUserProjectByUserId(String updateMessageCallbackRrl, String projectId, String userId) throws Exception {
        return   iCloudTalkSDKAppUserDao.updateUserProjectByUserId(updateMessageCallbackRrl,projectId,userId);
    }


    /**
     * <desc>
     *      从缓存中获取开发者信息
     * <desc/>
     *
     * @param token 用户token
     * @return
     * @author Qiang.S
     * @createDate 2019/09/16
     */
    @Override
    public PropertyUserInfoPO developerRetrieve(String token) {
        try {
            if (StringUtils.isBlank(token)) {
                return null;
            }
            //解密拿到手机号
            String appId;
            try {
                appId = UserTokenUtil.newAPPTokenDecrypt(token, userTokenKey);
            }catch (Exception e) {
                appId = null;
            }
            if (appId == null) {
                return null;
            }
            PropertyUserInfoPO propertyUserInfoPO = (PropertyUserInfoPO) redisService.getObject(RedisConstant.REDIS_CLOUDDEVICE_SDK_DEVELOPER_CACHE + appId,PropertyUserInfoPO.class);
            if (propertyUserInfoPO != null && token.equals(propertyUserInfoPO.getToken())) {
                //重置缓存时间
                redisService.set(RedisConstant.REDIS_CLOUDDEVICE_SDK_DEVELOPER_CACHE + appId,
                        RedisConstant.REDIS_CLOUDDEVICE_SDK_DEVELOPER_CACHE_TIME,propertyUserInfoPO);
                return propertyUserInfoPO;
            } else {
                return null;
            }
        }catch (RedisConnectionFailureException e){
            throw new DataAccessException("SDK_retrieve【从缓存中获取用户信息】redis连接失败") ;
        }
    }






}
